package com.dreamlin.banner.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import com.dreamlin.banner.R;

import java.lang.ref.WeakReference;
import java.util.List;

/**
 * banner的适配器
 */

public class BannerPagerAdapter<T> extends PagerAdapter {
    private List<T> mList;
    private Convert<T> mConvert;
    private WeakReference<Context> mContext;
    private int defaultImg = R.mipmap.ic_banner_error;//默认图片
    private int mRoundCorners = -1;
    private @LayoutRes
    int layoutId;

    /**
     * 默认
     *
     * @param defaultImg
     */
    public void setDefaultImg(int defaultImg) {
        this.defaultImg = defaultImg;
    }

    /**
     * 设置圆角
     *
     * @param mRoundCorners
     */
    public void setmRoundCorners(int mRoundCorners) {
        this.mRoundCorners = mRoundCorners;
    }

    /**
     * 点击回调
     */
    public interface OnClickImagesListener {
        void onImagesClick(int position);
    }

    private OnClickImagesListener mImagesListener;

    public void setOnClickImagesListener(OnClickImagesListener listener) {
        mImagesListener = listener;

    }

    public BannerPagerAdapter(List<T> list, WeakReference<Context> context,
                              Convert<T> convert, @NonNull @LayoutRes int layoutId) {
        this.mList = list;
        this.mContext = context;
        this.mConvert = convert;
        this.layoutId = layoutId;
    }

    @Override
    public int getCount() {
        return 500000;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View view = LayoutInflater.from(mContext.get()).inflate(layoutId, container, false);

        final int index = mList.size() == 0 ? 0 : position % mList.size();
//        LoadImage(mList.get(index), imageView);
        //OnClick
        if (mConvert != null) {
            mConvert.convert(mList.get(index), view);
        }
        view.setOnClickListener(v -> mImagesListener.onImagesClick(index));

        container.addView(view);
        return view;
    }


    public interface Convert<T> {
        void convert(T data, View holder);
    }

}